package com.atguigu.yygh.hosp.listener;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.mq.MqConst;
import com.atguigu.yygh.mq.RabbitService;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;


import com.rabbitmq.client.Channel;

import org.springframework.amqp.core.Message;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/*==========================================
      时 间:   2022-03-16
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@Component
public class OrderLisener {

    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private RabbitService rabbitService;

    // rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER,MqConst.ROUTING_ORDER,orderMqVo);
    @RabbitListener(bindings = {
            @QueueBinding(
                    value=@Queue(value = MqConst.QUEUE_ORDER,durable="true"),
                    exchange=@Exchange(value=MqConst.EXCHANGE_DIRECT_ORDER),
                    key=MqConst.ROUTING_ORDER
            )
    } )
    public void consume(OrderMqVo orderMqVo, Message message, Channel channel){
        if(orderMqVo.getAvailableNumber() != null){
            String scheduleId = orderMqVo.getScheduleId();
            Schedule schedule = scheduleService.getScheduleInfoById(scheduleId);
            //schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        }else{
            String scheduleId = orderMqVo.getScheduleId();
            Schedule schedule=scheduleService.getScheduleInfoByScheduleId(scheduleId);
            schedule.setAvailableNumber(schedule.getAvailableNumber()+1);
            scheduleService.update(schedule);
        }

        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_SMS, MqConst.ROUTING_SMS_ITEM, msmVo);
        }

        //
    }



}
